import { default as coordinateUtils } from './coordinate.js'

export {
  loadCss,
  loadJs,
  isFunction,
  isArrayOfArrays,
  isVisibleByBounds,
  coordinateUtils
}


/**
 * 加载css
 * @param {String} href
 */
function loadCss (href) {
  const node = document.createElement('link')
  node.rel = 'stylesheet'
  node.href = href
  document.getElementsByTagName('head')[0].appendChild(node)
}

/**
 * 加载js
 * @param {String} src
 */
function loadJs (src) {
  return new Promise((resolve) => {
    const script = document.createElement('script')
    script.type = 'text/javascript'
    script.async = false
    script.src = src
    document.getElementsByTagName('head')[0].appendChild(script)
    script.onload = function () {
      resolve()
    }
  })
}

function isFunction (v) {
  return typeof v === 'function'
}

function isArrayOfArrays (arr) {
  return Array.isArray(arr) && arr.every(v => Array.isArray(v))
}

/**
 * 判断位置是否在视图范围内
 * @returns {Boolean} true:在视图范围内，false:不在视图范围内
 */
function isVisibleByBounds (lnglat) {
  let visible = false
  const [west, south, east, north] = getViewerBounds.call(this)
  const [lng, lat] = lnglat
  if (west && south && east && north) {
    visible = Number(lng) >= west && Number(lng) <= east && Number(lat) >= south && Number(lat) <= north
  }
  return visible
}

/**
 * 获取当前视图范围
 * @returns {Array} [west, south, east, north]
 */
function getViewerBounds () {
  const extend = this.viewer.camera.computeViewRectangle()
  const canvas = this.viewer.scene.canvas
  let bounds = []
  if (extend) {
    bounds = [
      Cesium.Math.toDegrees(extend.west),
      Cesium.Math.toDegrees(extend.south),
      Cesium.Math.toDegrees(extend.east),
      Cesium.Math.toDegrees(extend.north)
    ]
  } else {
    const coordToLonlat = (viewer, [x, y]) => {
      const d2 = new Cartesian2(x, y)
      const ellipsoid = viewer.scene.globe.ellipsoid
      //2D转3D世界坐标
      const d3 = viewer.camera.pickEllipsoid(d2, ellipsoid)
      if (d3) {
        //3D世界坐标转弧度
        const upperLeftCartographic = ellipsoid.cartesianToCartographic(d3)
        //弧度转经纬度
        const lng = CesiumMath.toDegrees(upperLeftCartographic.longitude)
        const lat = CesiumMath.toDegrees(upperLeftCartographic.latitude)
        return { lng, lat }
      }
    }
    const { clientWidth, clientHeight } = canvas

    const { lng: upperLng, lat: upperLat } = coordToLonlat(this.viewer, [0, 0])
    const { lng: lowerLng, lat: lowerLat } = coordToLonlat(this.viewer, [clientWidth, clientHeight])
    if (upperLng && upperLat && lowerLng && lowerLat) {
      bounds = [
        upperLng,
        upperLat,
        lowerLng,
        lowerLat
      ]
    }
  }
  return bounds
}